package org.wmq.travelagency02.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wmq.travelagency02.model.Entity.Result;
import org.wmq.travelagency02.model.Entity.Route;
import org.wmq.travelagency02.model.VO.RouteQueryVO;
import org.wmq.travelagency02.service.RouteService;
import org.wmq.travelagency02.service.ScenicSpotService;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/route")
@RequiredArgsConstructor
public class RouteController {
    private final RouteService routeService;
    private final ScenicSpotService scenicSpotService;

    @GetMapping("/{id}")
    public Result<RouteQueryVO> getById(@PathVariable Long id) {
        Route route = routeService.getById(id);
        if (route == null){
            return Result.error("路线不存在");
        }
        RouteQueryVO result = new RouteQueryVO();
        result.setId(id);
        result.setName(route.getName());
        for (Long scenicSpotId : route.getContent()) {
            result.getContent().add(this.scenicSpotService.getById(scenicSpotId));
        }
        return Result.ok(result);
    }

    @PostMapping
    public Result<Void> save(@RequestBody Route route) {
        route.setCreateTime(LocalDateTime.now());
        route.setUpdateTime(LocalDateTime.now());
        routeService.save(route);
        return Result.ok();
    }

    @PutMapping
    public Result<Void> update(@RequestBody Route route) {
        route.setUpdateTime(LocalDateTime.now());
        if (routeService.updateById(route)){
            return Result.ok();
        }
        return Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        if (routeService.removeById(id)){
            return Result.ok();
        }
        return Result.error("删除失败");
    }

    @GetMapping("/page/{pageNo}/{pageSize}")
    public Result<List<Route>> getPage(@PathVariable Long pageNo, @PathVariable Long pageSize){
        return Result.ok(routeService.page(pageNo,pageSize));
    }

    @GetMapping("/all")
    public Result<List<Route>> getAll(){
        return Result.ok(routeService.list());
    }
}
